<template>

  <div class="container-wrapper">
    <div class="row-padding justify-center container-xxl container-row">
      <div class="wrapper">
        <div class="column">
          <form @submit.prevent.stop="onSubmit" class="q-gutter-md">
            <label for="customer_email">Email</label>
            <q-input
                ref="emailRef"
                :rules="emailRules"
                id="customer_email"
                outlined
                v-model="email"
                style="width: 100%"
                color="grey"
                lazy-rules
                placeholder="Email"/>
            <label for="customer_password">Password</label>
            <q-input
                ref="passwordRef"
                :rules="passwordRules"
                id="customer_password"
                outlined
                v-model="password"
                style="width: 100%"
                color="grey"
                lazy-rules
                placeholder="Password"
            >
            </q-input>
            <div class="submit">
              <q-btn
                  rounded
                  dense
                  color="black"
                  size="lg"
                  label="Login"
                  no-caps
                  type="submit"
              />
              <div style="text-align: end;">

                <span style="display: block;" >
                  <a class="Forgot" href="javascript:;" >Forgot your password?</a>
                </span>

                <span style="display: block;">
                  <strong >
                    <router-link class="Sign" to="/pc/register" id="customer_register_link">New Customer? Sign Up!</router-link>
                  </strong>
                </span>
              </div>
            </div>
            <q-btn
              size="15px"
              color="black"
              icon="fab fa-google"
              label="Login with Google"
              @click="handleGoogleLogin"
              style="width: 100%; margin-top: 20px"
            />
          </form>
        </div>
      </div>
  </div>
</div>
</template>

<script setup lang='ts'>
import {onMounted, ref} from 'vue'
import { useQuasar } from 'quasar'
import { userInfo, userLogin } from "../../api/userApi";
import { userStore } from '@/store/user.ts';
import { useRouter } from "vue-router";
import { oauthLogin, oauthUserInfo } from "../../api/oauth";

const router = useRouter()
const userstore = userStore()
const $q = useQuasar()
const email = ref(null)
const emailRef = ref(null)
const password = ref(null)
const passwordRef = ref(null)

const isValidEmail = (email) => {
  // 定义 email 格式的正则表达式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

  // 使用正则表达式检查 email 格式
  return emailRegex.test(email);
}
const emailRules = [
    val => (val && val.length > 0) || 'Please type something',
    val => isValidEmail(val) || `Please enter the correct email address.`
]
const passwordRules = [
    val => (val && val.length > 3 && val.length < 17) || 'Password length: 3 to 16',
]

const onSubmit = ()=> {
  emailRef.value.validate()
  passwordRef.value.validate()

  if (emailRef.value.hasError || passwordRef.value.hasError) {
    // form has error

  }else {
    userLogin({
      email: email.value,
      password: password.value,
    }).then((res) => {
      userstore.setToken(res.data.token)
      $q.notify({
        type: 'positive',
        message: "用户登录成功",
        position: "top"
      })
      router.push("/pc/Account")
    }).catch((err) => {
      console.log(err)
    });
  }
}

const handleGoogleLogin = () => {
  // 1. 获取登录URL
  oauthLogin().then((res) => {
    // 2. 存储 state 到 sessionStorage
    const state = new URL(res.redirect_url).searchParams.get('state')
    if (state) {
      sessionStorage.setItem('oauth_state', state)
    }

    // 3. 重定向到 Google
    window.location.href = res.redirect_url
  }).catch((err) => {
    $q.notify({
      type: 'negative',
      message: "登录失败: " + err.message,
      position: "top"
    })
  })
}

onMounted(() => {
  if (userstore.userInfo.token && userstore.userInfo.token != "") {
    userInfo().then((res) => {
      router.push("/pc/Account")
    }).catch((err) => {
      router.push("/pc/Login")
    });
  }else{
    router.push("/pc/Login")
  }
})

</script>

<style scoped lang='less'>
label{
  padding-bottom: 5px;
  display: inline-block;
  font-size: 19px;
  font-weight: 500;
}
.wrapper{
  padding: 0 50px 100px;
  .column{
    max-width: 480px;
  }
  .q-input{
    padding-bottom: 15px;
  }
}
.submit{
  padding-top: 20px;
  margin-bottom: 40px;
  .q-btn{
    width: 150px;
  }
  .Forgot, .Sign{
    &:hover{
      color: #26A69A;
      font-weight: bolder;
    }
  }
}
</style>